package org.catspaw.cherubim.serialize;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.ObjectBuffer;

public class KryoSerializer implements Serializer {

	private static final Kryo	kryo					= new Kryo();
	private int					bufferInitialCapacity	= -1;
	private int					bufferMaxCapacity		= -1;
	static {
		kryo.setRegistrationOptional(true);
	}

	public KryoSerializer() {
	}

	public KryoSerializer(int bufferInitialCapacity, int bufferMaxCapacity) {
		this.bufferInitialCapacity = bufferInitialCapacity;
		this.bufferMaxCapacity = bufferMaxCapacity;
	}

	public byte[] serialize(Object obj) {
		Class<?> type = obj.getClass();
		kryo.getRegisteredClass(type);
		ObjectBuffer buffer = createObjectBuffer();
		return buffer.writeClassAndObject(obj);
	}

	public Object deserialize(byte[] bs) {
		ObjectBuffer buffer = createObjectBuffer();
		return buffer.readClassAndObject(bs);
	}

	protected ObjectBuffer createObjectBuffer() {
		if (bufferInitialCapacity > 0 && bufferMaxCapacity > 0) {
			return new ObjectBuffer(kryo, bufferInitialCapacity,
					bufferMaxCapacity);
		} else if (bufferMaxCapacity > 0) {
			return new ObjectBuffer(kryo, bufferMaxCapacity);
		} else {
			return new ObjectBuffer(kryo);
		}
	}

	public int getBufferInitialCapacity() {
		return bufferInitialCapacity;
	}

	public int getBufferMaxCapacity() {
		return bufferMaxCapacity;
	}

	public void setBufferInitialCapacity(int bufferInitialCapacity) {
		this.bufferInitialCapacity = bufferInitialCapacity;
	}

	public void setBufferMaxCapacity(int bufferMaxCapacity) {
		this.bufferMaxCapacity = bufferMaxCapacity;
	}
}
